/*
 *   Copyright (C) 2010  Jens Kieselbach
 * 
 *   This program is free software: you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation, either version 3 of the License, or
 *   (at your option) any later version.
 * 
 *   This program is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 * 
 *   You may obtain a copy of the License at http://www.gnu.org/licenses/gpl.html
 */

package de.kieselbach.grunner.io

import de.kieselbach.grunner.value.*
import java.util.logging.*
import java.text.*

class TcxReader {

    static List readFile(File file, int timecorrection) {

        def activities = [] as List
        def dateformat = new SimpleDateFormat("yyyy-MM-ddHH:mm:ss")
        
        try {
            file.withInputStream {input ->
                def result = new XmlSlurper().parse(input)

                 result.'Activities'.'Activity'.each() {xmlact ->

                    def act = new Activity()
                    act.sport = xmlact.'@Sport'

                    int tpcount = 0
                    int bpm = 0
                    int maxbpm = 0

                    xmlact.'Lap'.each() {xmllap ->

                        if(act.laps == 0) {
                            def dt = xmllap.'@StartTime' as String
                            if(dt.length() >= 19) {
                                act.date = dateformat.parse(dt.substring(0, 10) + dt.substring(11, 19))
                                if(timecorrection != 0) {
                                    act.date.time = act.date.time + (1000 * 60 * 60 * timecorrection)
                                }
                            }

                            act.duration = xmllap.'TotalTimeSeconds'.text() as BigDecimal
                            act.distance = xmllap.'DistanceMeters'.text() as BigDecimal
                            act.calories = xmllap.'Calories'.text() as int

                            act.maximumPace = xmllap.'MaximumSpeed'.text() as BigDecimal
                            act.maximumPace = 1000 / act.maximumPace
                        }
                        else {
                            act.duration += xmllap.'TotalTimeSeconds'.text() as BigDecimal
                            act.distance += xmllap.'DistanceMeters'.text() as BigDecimal
                            act.calories += xmllap.'Calories'.text() as int
                        }

                        xmllap.'Track'.'Trackpoint'.each() {tp ->

                            def str = tp.'DistanceMeters'.text()
                            if(str != null && str.length() > 0) {
                            //    act.distance += str as BigDecimal
                            }

                            str = tp.'HeartRateBpm'.'Value'.text()
                            if(str != null && str.length() > 0) {
                                int val = str as int
                                bpm += val
                                if(val > maxbpm) {
                                    maxbpm = val
                                }
                            }

                            tpcount++
                        }

                        act.laps++
                    }

                    if(tpcount > 0) {
                        act.maximumHeartRate = maxbpm
                        act.averageHeartRate = bpm / tpcount
                    }

                    if(act.distance > 0 && act.duration > 0) {
                        act.averagePace = act.duration / act.distance * 1000
                    }

                    if(act.laps > 0) {
                        activities << act
                    }
                }
            }

            return activities
        }
        catch (Exception exc) {
            Logger.getLogger(getClass().name).log(Level.WARNING, 'Could not read TCX file: ' + file.toString(), exc)
            return null;
        }
    }
}

